package org.example.yuaiagent.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.yuaiagent.constant.SysConstant;
import org.example.yuaiagent.mapper.UserMapper;
import org.example.yuaiagent.model.entity.User;
import org.example.yuaiagent.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.UUID;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    static public ThreadLocal<User> currentUser = new ThreadLocal<>();
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;
    public User getSafetyUser(String id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return null;
        }
        //脱敏处理
        user.setPassword(null);
        return user;
    }


    public User userRegister(User user) {
        String userAccount = user.getUsername();
        String userPassword = user.getPassword();
        String email = user.getEmail();
        String phone = user.getPhone();
        user.setId(UUID.randomUUID().toString());
        user.setPassword(userPassword);
        user.setEmail(email);
        user.setPhone(phone);
        user.setUsername(userAccount);
        user.setAvatar("https://cdn.jsdelivr.net/gh/yuaiagent/yuaiagent@main/logo.png");
        user.setNickname("用户_"+UUID.randomUUID().toString().substring(0, 4));
        userMapper.insert( user);
        user.setPassword(null);
        return user;
    }


    public User userLogin(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        queryWrapper.eq(User::getPassword, user.getPassword());
        User loginUser = userMapper.selectOne(queryWrapper);
        if (loginUser == null) {
            return null;
        }
        //缓存到redis,设置过期时间
        stringRedisTemplate.opsForValue().set(SysConstant.loing_user_key +loginUser.getId(), JSON.toJSONString(loginUser));
        stringRedisTemplate.expire(SysConstant.loing_user_key+loginUser.getId(), Duration.ofDays(30*60*1000));
        loginUser.setPassword(null);
        return loginUser;
    }

    public boolean userLogout(User user) {
        stringRedisTemplate.delete("user:login:token"+user.getUsername());
        return true;
    }
}
